package cz.muni.fi.pa165.web.security;

import cz.muni.fi.pa165.api.PickerService;
import cz.muni.fi.pa165.api.dto.PickerDTO;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author Matej Cimbora
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PickerService service;
    private ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pa165.web.security.backdoor");

    @Override
    public UserDetails loadUserByUsername(String nick) throws UsernameNotFoundException {
        if (!nick.isEmpty() && nick.equals("rest")) {
            GrantedAuthority auth = new SimpleGrantedAuthority(PickerDTO.UserRole.ROLE_ADMIN.toString());
                List<GrantedAuthority> list = new ArrayList<>();
                list.add(auth);
                return new User("rest", "rest", list);
        }
        //Hard wired admin account for easier presentation of functionality (nick:admin pass:admin)
        if(!nick.isEmpty() && nick.equals(rb.getString("userName"))) {
            GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_ADMIN");
                List<GrantedAuthority> list = new ArrayList<>();
                list.add(auth);
                return new User(rb.getString("userName"), rb.getString("password"), list);
        }
        
        for (PickerDTO user : service.findAllPickers()) {
            if (user.getNickName().equals(nick)) {
                GrantedAuthority auth = new SimpleGrantedAuthority(user.getUserRole().toString());
                List<GrantedAuthority> list = new ArrayList<>();
                list.add(auth);
                return new User(user.getNickName(), user.getPassword(), list);
            }
        }
        throw new UsernameNotFoundException("User not found");
    }
}
